package com.tf_cut.backend.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.UUID;

import org.dom4j.DocumentException;

import org.apache.commons.codec.binary.Base64;
import org.dom4j.io.SAXReader;

import com.tf_cut.backend.request.DefaultMybankClient;
import com.tf_cut.backend.request.DefaultSigner;
import com.tf_cut.backend.request.DocumentMobile;
import com.tf_cut.backend.request.DocumentResponMobile;
import com.tf_cut.backend.request.Head;
import com.tf_cut.backend.request.MerchantprodMerchantUploadphotoRequest;
import com.tf_cut.backend.request.MerchantprodMerchantUploadphotoRequestModel;
import com.tf_cut.backend.request.MerchantprodMerchantUploadphotoResponse;
import com.tf_cut.backend.request.MerchantprodMerchantUploadphotoResponseModel;
import com.tf_cut.backend.request.MybankApiException;
import com.tf_cut.backend.request.MybankClient;
import com.tf_cut.backend.request.ReceiptHead;
import com.tf_cut.backend.request.Request;
import com.tf_cut.backend.request.Signer;
import com.tf_cut.backend.seller.vo.SellerAndAccountVo;
import com.tf_cut.backend.service.vo.ServiceInfoVo;
import com.thoughtworks.xstream.XStream;

public class MyConfig {

	public static String serverUploadUrl = "http://bkgwdev.dl.alipaydev.com/ant/mybank/merchantprod/merchant/uploadphoto.htm";
	public static String receiptUrl = "http://bkgwdev.dl.alipaydev.com/open/lite/api/common/request.htm";
	public static String serverUrl = "https://fcsupergw.mybank.dl.alipaydev.com/open/api/common/request2.htm";
	public static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+DjjKuBYNScrhp7/+yf/vqsZbyWAMuvLZ76rv9wLA3XTCY1Cb3xxm7xvux/OzhzDlQdURRrEhjjsVdP9Bx0Ig5yfGyDec/4Z50dcRgqsu17QU/m2WXHEwFd4yBAGomWXzy/q7+8JJ9YoTraSDfKhfV3qWx7/vBzqk0QNzZ3AgFwSMiP5Azz8K2GhkHWxbVLlji9+/oRL5yj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EZ043VlNrapD8KLsFNu6S/tGIzPiz8i28qu6DQjRPUnxLL6ruPjtlGKbn0ykomM7BUrl6Nhi3qf0hV7wh0cWx4g7AJh97oQz9a/j+pc56WBMo2eOM9cUeZDOb3Qp1AoGAQwB8ndcxkt4UCfC+87Rpy5yrxVuaVKDZfTIy4qpuLrHRqCIHvAl41EnJTE8MPIemXhdTmPeLmGWe7KjGDo0F0GPRqBMVKrLrCnM52FUx/Wp5P2h8ZVXvm7TR5/b3jhCb7qC0gjey+HunyEn78H9Vxty4XzcSlF0zu8uVUSgwIJ8=";
	public static String mybankPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOb4B1dnwONcW0RoJMa0IOq3O6jiqnTGLUpxEw2xJg+c7wsb6DBy5CAoR0w2ZjZ/BjKxGIQ+DoDg3NsHJeyuEjNF0/Ro/R5xVpFC5z4cBVSC2/gddz4a1EoGDJewML/Iv0yIw7ylB86++h23nRd079c5S9RZXurBfnLW2Srhqk2QIDAQAB";
	public static String appId = "2021042700000312";
	public static String isvOrgId = "202211000000000000312";

	public static String signType = MybankConstants.SIGN_TYPE_RSA;
	public static String charset = MybankConstants.CHARSET_UTF8;

	private static Signer signer = new DefaultSigner(MyConfig.privateKey);

	/**
	 * 入驻及其他
	 * @param body
	 * @param function
	 * @return
	 */
	public static String beanToXml(Object body,String function) {
		DocumentMobile root = new DocumentMobile();

		Request caseFile = new Request();
		root.setRequest(caseFile);
		Head head = new Head();
		head.setFunction(function);
		caseFile.setHead(head);
		caseFile.setBody(body);

		// 创建xstream对象
		XStream xStream = new XStream();
		// 给指定类起别名
		xStream.alias("document", DocumentMobile.class);
		// 将对象转换成xml字符串
		String xml = xStream.toXML(root);

		return xml;
	}
	
	/**
	 * 查询回单流水
	 * @param body
	 * @param function
	 * @return
	 */
	public static String receiptToXml(Object body,String function) {
		DocumentMobile root = new DocumentMobile();

		Request caseFile = new Request();
		root.setRequest(caseFile);
		ReceiptHead head = new ReceiptHead();
		head.setFunction(function);
		caseFile.setHead(head);
		caseFile.setBody(body);

		// 创建xstream对象
		XStream xStream = new XStream();
		// 给指定类起别名
		xStream.alias("document", DocumentMobile.class);
		// 将对象转换成xml字符串
		String xml = xStream.toXML(root);

		return xml;
	}
	
	/**
	 * 图片上传
	 * @param body
	 * @param function
	 * @return
	 */
	public static String ResponBeanToXml(Object body,String function) {
		DocumentResponMobile root = new DocumentResponMobile();

		Request caseFile = new Request();
		root.setResponse(caseFile);
		Head head = new Head();
		head.setFunction(function);
		caseFile.setHead(head);
		caseFile.setBody(body);

		// 创建xstream对象
		XStream xStream = new XStream();
		// 给指定类起别名
		xStream.alias("document", DocumentResponMobile.class);
		// 将对象转换成xml字符串
		String xml = xStream.toXML(root);

		return xml;
	}

	public static String Base64(SellerAndAccountVo svo) throws UnsupportedEncodingException {
		String json = "{\"LegalPerson\":\"" + svo.getSellerCompanyName() + "\",\"PrincipalMobile\":\""
				+ svo.getSellerMobile() + "\",\"PrincipalCertType\":\"01\",\"PrincipalCertNo\":\""
				+ svo.getSellerCardCode() + "\",\"PrincipalPerson\":\"" + svo.getSellerPersonName()
				+ "\",\"bussAuthParam\":{\"BussAuthType\":\"12\",\"BussAuthNo\":\"" + svo.getTaxPayerCode()
				+ "\"},\"CertPhotoA\":\"" + uploadFile("01", svo.getCertPhotoA()) + "\",\"CertPhotoB\":\""
				+ uploadFile("02", svo.getCertPhotoB()) + "\",\"LicensePhoto\":\""
				+ uploadFile("03", svo.getBusinessLicenseFile()) + "\",\"IndustryLicensePhoto\":\""
				+ uploadFile("05", svo.getIndustryLicensePhoto()) + "\"}";

		final Base64 base64 = new Base64();
		final byte[] textByte = json.getBytes("UTF-8");
		// 编码
		final String encodedText = base64.encodeToString(textByte);
		return encodedText;
	}
	
	
	public static String serviceBase64(ServiceInfoVo svo) throws UnsupportedEncodingException {
		String json = "{\"LegalPerson\":\"" + svo.getServiceCom() + "\",\"PrincipalMobile\":\""
				+ "" + "\",\"PrincipalCertType\":\"01\",\"PrincipalCertNo\":\""
				+ svo.getServiceCardCode() + "\",\"PrincipalPerson\":\"" + svo.getServiceLegal()
				+ "\",\"bussAuthParam\":{\"BussAuthType\":\"12\",\"BussAuthNo\":\"" + svo.getServiceCode()
				+ "\"},\"CertPhotoA\":\"" + uploadFile("01", svo.getCertPhotoA()) + "\",\"CertPhotoB\":\""
				+ uploadFile("02", svo.getCertPhotoB()) + "\",\"LicensePhoto\":\""
				+ uploadFile("03", svo.getBusinessLicenseFile()) + "\",\"AuthorizeCoPhoto\":\""
				+ uploadFile("35", svo.getAuthorizePhoto()) + "\",\"QualificationPhoto\":\""
				+ uploadFile("32", svo.getQualifiPhoto()) + "\",\"upstreamCoPhoto\":\""
				+ uploadFile("33", svo.getUpstreamPhoto()) + "\",\"downstreamCoPhoto\":\""
				+ uploadFile("34", svo.getDownstreamPhoto()) + "\"}";

		final Base64 base64 = new Base64();
		final byte[] textByte = json.getBytes("UTF-8");
		// 编码
		final String encodedText = base64.encodeToString(textByte);
		return encodedText;
	}
	
	public static String Base64Bank(ServiceInfoVo svo) throws UnsupportedEncodingException {
		String json = "{\"BankCardNo\":\"" + svo.getServiceAccount() + "\",\"BankCertName\":\""
				+ svo.getServiceCom() + "\",\"AccountType\":\""
				+ "02" + "\",\"ContactLine\":\""
				+ svo.getContactLine() + "\"}";
		final Base64 base64 = new Base64();
		final byte[] textByte = json.getBytes("UTF-8");
		// 编码
		final String encodedText = base64.encodeToString(textByte);
		return encodedText;
	}
	
	public static String Base64String(String MerchantDetail){
		byte[] b = MerchantDetail.getBytes();
		Base64 base64 = new Base64();
		b = base64.decode(b);
		MerchantDetail = new String(b);
		return MerchantDetail;
		
	}
	

	public static String uploadFile(String photoType, String picture) {
		if(photoType.equals("05")){
			return "";
		}
		if(picture == null || picture.equals("")){
			return "";
		}
		String photoUrl = null;
		MybankClient mybankClient = new DefaultMybankClient(serverUploadUrl, privateKey, mybankPublicKey);
		MerchantprodMerchantUploadphotoRequest merchantUploadphotoRequest = new MerchantprodMerchantUploadphotoRequest();
		MerchantprodMerchantUploadphotoRequestModel photoUploadVo = new MerchantprodMerchantUploadphotoRequestModel();
		photoUploadVo.setIsvOrgId(isvOrgId);
		photoUploadVo.setPhotoType(photoType);
		photoUploadVo.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		File file = new File("/home/ubuntu/data/uploadFile/mobile/upload/" + picture);// 测试项目文件，正常调用时可以通过file对象传参
		photoUploadVo.setPicture(file);
		photoUploadVo.setFunction("ant.mybank.merchantprod.merchant.uploadphoto");
		photoUploadVo.setVersion("1.0.0");
		photoUploadVo.setAppId(appId);
		photoUploadVo
				.setReqTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern(MybankConstants.DATE_TIME_FORMAT)));
		photoUploadVo.setSignature(urlencode(photoUploadVo));
		merchantUploadphotoRequest.setUploadphotoRequestModel(photoUploadVo);
		try {
			System.out.println("1");
			MerchantprodMerchantUploadphotoResponse uploadphotoResponse = mybankClient.execute(merchantUploadphotoRequest);
			System.out.println("2");
			MerchantprodMerchantUploadphotoResponseModel uploadphotoResponseModel = uploadphotoResponse
					.getMerchantUploadphoto().getMerchantUploadphotoResponseModel();
			System.out.println("3");
			// 服务端返回报文
			System.out.println("服务端返回报文=" + uploadphotoResponse.getXmlContent());
			SAXReader reader = new SAXReader();
			try {
				org.dom4j.Document doc = reader
						.read(new ByteArrayInputStream(uploadphotoResponse.getXmlContent().getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();

					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							String resultStatus = element3.elementText("ResultStatus");
							String resultCode = element3.elementText("ResultCode");
						}
						photoUrl = element2.elementText("PhotoUrl");
						//String outTradeNo = element2.elementText("OutTradeNo");
					}
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (MybankApiException e) {
			e.printStackTrace();
		}

		return photoUrl;
	}

	public static String urlencode(MerchantprodMerchantUploadphotoRequestModel photoUploadVo) {
		String para = "IsvOrgId=" + photoUploadVo.getIsvOrgId() + "&PhotoType=" + photoUploadVo.getPhotoType()
				+ "&OutTradeNo=" + photoUploadVo.getOutTradeNo() + "&Function=" + photoUploadVo.getFunction()
				+ "&Version=" + photoUploadVo.getVersion() + "&AppId=" + photoUploadVo.getAppId() + "&ReqTime="
				+ photoUploadVo.getReqTime();
		try {
			para = java.net.URLEncoder.encode(para, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return para;
	}

}
